package com.blyat.xsoft.kernel.component.mq.rocketmq;

import com.blyat.xsoft.kernel.component.mq.rocketmq.annotation.Consumer;
import com.blyat.xsoft.kernel.component.mq.rocketmq.annotation.RocketMqScan;
import com.blyat.xsoft.kernel.component.mq.rocketmq.annotation.Transactor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: syh
 * @Date: 2020/8/10
 * @Description:
 */
public class RocketMQBeanRegistrar implements ImportBeanDefinitionRegistrar
        , ResourceLoaderAware, EnvironmentAware {
    private static final Logger log = LoggerFactory.getLogger(RocketMQBeanRegistrar.class);
    private ResourceLoader resourceLoader;
    private Environment environment;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        // 屏蔽rocketmq log4j2相关配置
        System.setProperty("rocketmq.client.log.loadconfig", "false");

        String nameServer = environment.getProperty("rocketmq.name-server", "");
        if ("".equals(nameServer)) {
            log.warn("no rocketmq bean will be register. because rocketmq.name-server is empty.");
            return;
        }
        RocketMQScanner scanner = new RocketMQScanner(registry);
        scanner.setResourceLoader(this.resourceLoader);

        AnnotationAttributes annotationAttrs =
                AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(RocketMqScan.class.getName()));

        scanner.addIncludeFilter(new AnnotationTypeFilter(Consumer.class));
        scanner.addIncludeFilter(new AnnotationTypeFilter(Transactor.class));

        List<String> basePackages = new ArrayList<>();
        for (String pkg : annotationAttrs.getStringArray("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }

        scanner.scan(StringUtils.toStringArray(basePackages));
    }
}
